package com.hk.web.domain.lifeCycle.repository;

import com.hk.commons.enums.Whether;
import com.hk.web.domain.entity.UserRole;
import com.hk.web.dto.UserRoleQueryDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Antinomy on 17/1/10.
 */
public class UserRoleSpecification {

    public static Specification<UserRole> buildFromDTO(UserRoleQueryDTO dto) {
        return (root, query, builder) -> {

            ArrayList<Predicate> list = new ArrayList<>();

            if (dto.getName() != null) {
                list.add(builder.like(root.<String>get("name"), "%"+dto.getName()+"%"));
            }

            if (StringUtils.isNoneBlank(dto.getUuid())) {
                list.add(builder.equal(root.<String>get("uuid"), dto.getUuid()));
            }

            if (dto.getDeleted() != null) {
                list.add(builder.equal(root.<Whether>get("deleted"), dto.getDeleted()));
            }

            Predicate[] predicates = new Predicate[list.size()];
            predicates = list.toArray(predicates);

            return builder.and(predicates);
        };
    }
}
